<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架状态" prop="productFlag">
        <el-select v-model="queryParams.productFlag" placeholder="请选择上架状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.product_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['projects:SlProduct:add']"
        >新增产品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['projects:SlProduct:remove']"
        >删除产品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['projects:SlProduct:export']"
        >导出产品</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SlProductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品类型" align="center" prop="categoryId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_type" :value="scope.row.categoryId"/>
          </template>
        </el-table-column>
      <el-table-column label="名称" align="center" prop="productName" />
      <el-table-column label="封面图" align="center" prop="productImg">
        <template slot-scope="scope">
         <img :src="scope.row.productImg" alt="图片描述" width="50" height="50" />
       </template>
      </el-table-column>
      <el-table-column label="首次体验价" align="center" prop="productFirstPrice" />
      <el-table-column label="单次价格" align="center" prop="productPrice" />
      <el-table-column label="包干价格" align="center" prop="productPackagePrice" />
      <el-table-column label="销量" align="center" prop="saleNum" />
      <el-table-column label="是否推荐" align="center" prop="ifTop" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ifTop" :value="scope.row.ifTop"/>
          </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" prop="productFlag" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_flag" :value="scope.row.productFlag"/>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-picture-outline"
            @click="handleUpDownPro(scope.row)"
            v-hasPermi="['projects:SlProduct:edit']"
          >上下架</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['projects:SlProduct:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['projects:SlProduct:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改森理产品包对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-tabs :activeName="activeName">
           <el-tab-pane label="产品基础信息" name="1">
             <el-row style="margin-top: 30px">
               <el-col :span="12">
                  <el-form-item label="产品类型" prop="categoryId">
                    <el-select v-model="form.categoryId" placeholder="请选择产品类型" clearable :style="{width: '100%'}">
                      <el-option v-for="(item, index) in dict.type.product_type" :key="index" :label="item.label"
                        :value="item.value" :disabled="item.disabled"></el-option>
                    </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="名称" prop="productName">
                    <el-input v-model="form.productName" placeholder="请输入产品名称" />
                  </el-form-item>
               </el-col>
             </el-row>
             <el-row style="margin-top: 30px">
               <el-col :span="12">
                  <el-form-item label="体验价" prop="productFirstPrice">
                    <el-input type = "number" v-model="form.productFirstPrice" placeholder="请输入产品首次体验价" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="单次价格" prop="productPrice">
                    <el-input type = "number" v-model="form.productPrice" placeholder="请输入产品单次价格" />
                  </el-form-item>
               </el-col>
             </el-row>
             <el-row style="margin-top: 30px">
               <el-col :span="12">
                  <el-form-item label="包干价格" prop="productPackagePrice">
                    <el-input type = "number" v-model="form.productPackagePrice" placeholder="请输入产品包干价格" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="销量" prop="saleNum">
                    <el-input type = "number" v-model="form.saleNum" placeholder="请输入产品销售数量" />
                  </el-form-item>
               </el-col>
             </el-row>
             <el-row style="margin-top: 30px">
               <el-col :span="12">
                  <el-form-item label="是否推荐" prop="ifTop">
                    <el-select v-model="form.ifTop" placeholder="请选择推荐状态" clearable :style="{width: '100%'}">
                      <el-option v-for="(item, index) in dict.type.ifTop" :key="index" :label="item.label"
                        :value="item.value" :disabled="item.disabled"></el-option>
                    </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                <el-form-item label="产品描述" prop="productDesc">
                  <el-input v-model="form.productDesc" placeholder="请输入产品描述" />
                </el-form-item>
               </el-col>
             </el-row>
            </el-tab-pane>
              <el-tab-pane label="图片添加" name="2"> 
                <!-- 1. 封面图上传（单张） -->
                <el-form-item label="封面图" prop="productImg" required>
                  <el-upload 
                    ref="productImgUpload" 
                    :file-list="productImgfileList" 
                    :action="uploadUrl" 
                    :headers="headers"
                    :auto-upload="true" 
                    :before-upload="handleBeforeUpload"  
                    :on-success="handleCoverUploadSuccess"  
                    :on-error="handleUploadError" 
                    :on-remove="handleCoverRemove" 
                    :limit="1"
                    list-type="picture-card"
                    accept="image/jpeg,image/png,image/jpg"  
                    name="file">
                    <!-- 上传加载中显示图标 -->
                    <i v-if="!coverUploadLoading" class="el-icon-plus"></i>
                    <el-loading v-else type="spinner" size="small"></el-loading>
                    <div slot="tip" class="el-upload__tip">支持 JPG/PNG 格式，大小不超过 2MB</div>
                  </el-upload>
                </el-form-item>

                <!-- 2. 展示图上传（多张） -->
                <el-form-item label="展示图" prop="productShowImg" required>
                  <el-upload 
                    ref="productShowUpload" 
                    :file-list="productShowImgfileList" 
                    :action="uploadUrl" 
                    :headers="headers"
                    :auto-upload="true" 
                    :multiple="true"
                    :before-upload="handleBeforeUpload"  
                    :on-success="handleShowUploadSuccess"  
                    :on-error="handleUploadError" 
                    :on-remove="handleShowRemove"  
                    list-type="picture-card"
                    accept="image/jpeg,image/png,image/jpg" 
                    name="file">
                    <i v-if="!showUploadLoading" class="el-icon-plus"></i>
                    <el-loading v-else type="spinner" size="small"></el-loading>
                    <div slot="tip" class="el-upload__tip">支持 JPG/PNG 格式，大小不超过 2MB，可上传多张</div>
                  </el-upload>
                </el-form-item>
              </el-tab-pane>
        </el-tabs>
      </el-form>
      <div  class="element-drawer__button">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listSlProduct, getSlProduct, delSlProduct, addSlProduct, updateSlProduct } from "@/api/projects/SlProduct";
import { getToken } from "@/utils/auth";
export default {
  name: "SlProduct",
  dicts: ['product_flag','ifTop','product_type'],
  data() {
    return {
      activeName: "1",
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 新增：上传加载状态（避免重复上传）
      coverUploadLoading: false,  // 封面图上传中
      showUploadLoading: false,   // 展示图上传中
      productShowImgfileList: [],
      productImgfileList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 森理产品包表格数据
      SlProductList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: "",
        productImg: null,
        categoryId:null,
        productFirstPrice: null,
        productPrice: null,
        productPackagePrice: null,
        productFlag: null,
        ifTop:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询森理产品包列表 */
    getList() {
      this.loading = true;
      listSlProduct(this.queryParams).then(response => {
        this.SlProductList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: null,
        productImg: "",  // 重置为空字符串（原先是 null，可能导致异常）
        productShowImg: "",
        productFirstPrice: null,
        productPrice: null,
        productPackagePrice: null,
        productFlag: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      // 清空图片文件列表
      this.productImgfileList = [];
      this.productShowImgfileList = [];
      // 重置上传加载状态
      this.coverUploadLoading = false;
      this.showUploadLoading = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加森理产品包";
    },
        // -------------------------- 新增：统一图片上传前校验 --------------------------
    handleBeforeUpload(file) {
      // 1. 校验文件大小（≤2MB）
      const isLt2MB = file.size / 1024 / 1024 <= 2;
      if (!isLt2MB) {
        this.$message.error(`当前文件 ${file.name} 大小超过 2MB，请压缩后上传`);
        return false;
      }
      // 2. 校验文件格式（JPG/PNG）
      const isImg = ["image/jpeg", "image/png", "image/jpg"].includes(file.type);
      if (!isImg) {
        this.$message.error(`当前文件 ${file.name} 格式不支持，请上传 JPG/PNG 图片`);
        return false;
      }
      // 3. 开启上传加载状态
      if (file.type === "image/jpeg" || file.type === "image/png" || file.type === "image/jpg") {
        // 区分封面图/展示图（通过 upload 组件的 ref 判断，也可通过其他方式）
        const isCover = this.$refs.productImgUpload?.uploadFiles?.includes(file);
        isCover ? (this.coverUploadLoading = true) : (this.showUploadLoading = true);
      }
      return true;
    },
     // -------------------------- 优化：封面图上传成功 --------------------------
    handleCoverUploadSuccess(res, file) {
      // 关闭加载状态
      this.coverUploadLoading = false;
      if (res.code === 200) {
        // 清空原有封面图，确保只保留1张
        this.productImgfileList = [];
        // 按 el-upload 要求格式添加文件（name 用文件名，url 用返回的图片地址）
        this.productImgfileList.push({
          id: Date.now(),  // 新增：唯一标识（用于去重/删除）
          name: file.name,
          url: res.url
        });
        // 更新表单封面图字段（单张图无需用逗号拼接）
        this.form.productImg = res.url;
        this.$message.success("封面图上传成功");
      } else {
        this.handleUploadError(res, file);  // 统一走错误处理
      }
    },
        // -------------------------- 优化：展示图上传成功 --------------------------
    handleShowUploadSuccess(res, file) {
      this.showUploadLoading = false;
      if (res.code === 200) {
        // 检查是否已上传过相同文件（去重：按 url 或 文件名）
        const isDuplicate = this.productShowImgfileList.some(item => item.url === res.url);
        if (isDuplicate) {
          this.$message.warning(`文件 ${file.name} 已上传，无需重复添加`);
          return;
        }
        // 添加到展示图列表
        this.productShowImgfileList.push({
          id: Date.now(),
          name: file.name,
          url: res.url
        });
        // 更新表单展示图字段（多张图用逗号拼接）
        this.form.productShowImg = this.productShowImgfileList.map(item => item.url).join(",");
        this.$message.success(`展示图 ${file.name} 上传成功`);
      } else {
        this.handleUploadError(res, file);
      }
    },
        // -------------------------- 优化：上传失败处理 --------------------------
    handleUploadError(res, file) {
      // 关闭加载状态
      this.coverUploadLoading = false;
      this.showUploadLoading = true;
      // 移除错误文件（避免留在文件列表）
      const isCover = this.$refs.productImgUpload?.uploadFiles?.includes(file);
      if (isCover) {
        this.productImgfileList = this.productImgfileList.filter(item => item.url !== file.response?.url);
      } else {
        this.productShowImgfileList = this.productShowImgfileList.filter(item => item.url !== file.response?.url);
      }
      // 提示错误信息（优先用接口返回的 msg，没有则用默认）
      this.$message.error(res.msg || `文件 ${file.name} 上传失败，请重试`);
    },
        // -------------------------- 优化：封面图删除 --------------------------
    handleCoverRemove(file, fileList) {
      // 更新文件列表（保持与 el-upload 同步）
      this.productImgfileList = fileList;
      // 清空表单封面图字段（如果列表为空）
      this.form.productImg = fileList.length > 0 ? fileList[0].url : "";
      this.$message.info("封面图已删除");
    },

    // -------------------------- 优化：展示图删除 --------------------------
    handleShowRemove(file, fileList) {
      this.productShowImgfileList = fileList;
      // 重新拼接展示图 URL 到表单字段
      this.form.productShowImg = fileList.map(item => item.url).join(",");
      this.$message.info(`展示图 ${file.name} 已删除`);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset(); // 先执行原有重置逻辑
      const id = row.id || this.ids;
      getSlProduct(id).then(response => {
        this.form = response.data;
        const { productImg, productShowImg } = this.form;
        // 1. 封面图回显（处理空值，避免报错）
        this.productImgfileList = productImg 
          ? [{ id: Date.now(), name: "cover.jpg", url: productImg }]  // 按标准格式回显
          : [];
        // 2. 展示图回显（处理空值 + 避免二维数组）
        this.productShowImgfileList = productShowImg 
          ? productShowImg.split(",").map(url => ({  // 拆分后转成对象数组
              id: Date.now() + Math.random(),  // 随机唯一标识（避免重复）
              name: `show_${Date.now()}.jpg`,
              url: url
            }))
          : [];
        this.open = true;
        this.title = "修改森理产品包";
      });
    },
    /** 修改上架下架状态 */
    handleUpDownPro(row) {
      this.reset();
      this.form.id=row.id;
      if(row.productFlag==0){
        this.form.productFlag=1;
      }else{
        this.form.productFlag=0;
      }
      updateSlProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log(this.form)
        if (valid) {
          if (this.form.id != null) {
            updateSlProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSlProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除森理产品包编号为"' + ids + '"的数据项？').then(function() {
        return delSlProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('projects/SlProduct/export', {
        ...this.queryParams
      }, `SlProduct_${new Date().getTime()}.xlsx`)
    },
    /** 处理封面图删除 */
    handleRemoveSingle(file) {
      const index = this.productImgfileList.indexOf(file.url);
      if (index !== -1) {
        this.productImgfileList.splice(index, 1);
      }
      this.form.productImg = this.productImgfileList.join(",");
    },
    /** 处理展示图删除 */
    handleRemoveMore(file) {
      const index = this.productShowImgfileList.indexOf(file.url);
      if (index !== -1) {
        this.productShowImgfileList.splice(index, 1);
      }
      this.form.productShowImg = this.productShowImgfileList.join(",");
    }
  }
};
</script>
